﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml.Serialization;
using Editor.Utilities;

namespace Editor.Old
{
    [XmlInclude(typeof(Department))]
    public class Project : Element
    {
        private List<Department> departments = new List<Department>();
        
        public Project() 
        {
        }

        public Project(string name)
            : base(name)
        {
        }

        public override IList ChildElements
        {
            get
            {
                return departments;
            }
            set
            {
                departments = value as List<Department>;
            }
        }

        [XmlIgnore]
        public override string Path
        {
            get
            {
                string path = Name + ".proj";
                
                path = System.IO.Path.Combine(Name, path);

                return path;
            }
        }

        [XmlIgnore]
        public bool IsSaved { get; set; }

        [XmlIgnore]
        public bool IsLoaded { get; set; }

        public override Element CreateChildElement(string childElementName)
        {
            return new Department(childElementName);
        }

        public override void AddChildElement(Element element)
        {
            base.AddChildElement(element);
            IsSaved = false;
        }

        public override Element AddChildElement(string elementName)
        {
            Element elem = base.AddChildElement(elementName);
            
            IsSaved = false;

            return elem;
        }

        public override void RemoveChildElement(Element element)
        {
            base.RemoveChildElement(element);
            IsSaved = false;
        }

        public override void RemoveChildElement(string elementName)
        {
            base.RemoveChildElement(elementName);
            IsSaved = false;
        }
        
        public static Project Load(string fileName)
        {
            Project loadedProject = XMLWorker<Project>.DeserializeFromXML(fileName);

            loadedProject.UpdateParents();
            loadedProject.IsLoaded = true;
            loadedProject.IsSaved = true;

            return loadedProject; 
        }

        public void Save()
        {
            XMLWorker<Project>.SerializeToXML(this, Path);
            IsSaved = true;
        }

        public void UpdateParents()
        {
            updateParent(this);
        }

        private void updateParent(Element element)
        {
            foreach (Element child in element.ChildElements)
            {
                child.Parent = element;
                updateParent(child);
            }
        }
    }
}
